/**
 * 
 */
package com.ccjq.jq173.core.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

/**
 * @author xugang
 *
 */
public class UuidUtils {

	/**
	 * 获取唯一标识
	 * 
	 * @return 返回长度为19位纯数字唯一标识
	 */
	public static long generateShortUUID() {
		long t1 = 0x7FFFFFFF & System.currentTimeMillis();
		Random random = new Random();
		return t1 << 32 | Math.abs(random.nextInt());
	}

	/**
	 * 获取唯一标识
	 * 
	 * @param prefix 前缀
	 * @param length 长度(不包含前缀,最大长度19位;长度越短重复值产生的概率越高)
	 * @return 返回指定前缀和长度的唯一标识
	 */
	public static String generateShortUUID(String prefix, int length) {
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String shortUUID = String.valueOf(generateShortUUID());
		char[] uuidChars = uuid.toCharArray();
		char[] shortuuidChars = shortUUID.toCharArray();
		StringBuilder builder = new StringBuilder(StringUtils.isBlank(prefix) ? "" : prefix);
		if (length < 0) {
			length = shortUUID.length();
		}
		for (int i = 0; i < length; i++) {
			int index = Integer.parseInt(String.valueOf(shortuuidChars[i]));
			builder.append(String.valueOf(uuidChars[index]));
		}
		return builder.toString().toUpperCase();
	}

	/*
	 * 测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Set<String> stuNoSet = new TreeSet<String>();
		int count = 6;
		for (int i = 0; i < count; i++) {
			String studentNo = generateShortUUID("U", 10);
			stuNoSet.add(studentNo);
			System.out.println("studentNo = " + studentNo);
		}
		if (stuNoSet.size() == count) {
			System.out.println("测试生成" + count + "个学号，无重复！");
		} else {
			System.out.println("测试生成" + count + "个学号，重复个数:" + (count - stuNoSet.size()));
		}

		System.out.println("------------------------------------");

	/*	for (int i = 0; i < 10; i++) {
			String channelId = "" + generateShortUUID();
			System.out.println("channelId = " + channelId);
		}
		System.out.println(UUID.randomUUID().toString());*/
	}
}
